<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="日期" style="width: 308px">
                <el-date-picker
                    v-model="queryParams.date"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="支付方式" prop="payTypeId">
                <el-select v-model="queryParams.payTypeId" filterable placeholder="请搜索或选择支付方式">
                  <el-option
                      v-for="item in listStores"
                      :key="item.payTypeId"
                      :label="item.payTypeName"
                      :value="item.payTypeId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>


            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
<!--              <el-table-column label="客户编号" align="center" key="noticeId" prop="noticeId"  />-->
              <el-table-column label="日期" align="center" key="date" prop="date"  />

              <el-table-column label="支付方式名称" align="center" key="payCategoryName" prop="payCategoryName"  />

<!--              <el-table-column label="本日发生" align="center" key="本日发生" prop="businessType"  />-->
              <el-table-column label="本日发生" align="center" key="status">

                <template #default="scope">
                  {{ scope.row.businessType == 1 ? '本日发生' :'' }}

<!--                  <dict-tag :options="sys_company_disable" :value="scope.row.status" />-->
                </template>
              </el-table-column>
              <el-table-column label="昨日余额" align="center" key="yesterdayBalance" prop="yesterdayBalance"  />
              <el-table-column label="今日入账金额" align="center" key="nowPayAmount" prop="nowPayAmount"  />
              <el-table-column label="今日退款金额" align="center" key="nowRefundAmount" prop="nowRefundAmount"  />
              <el-table-column label="今日余额" align="center" key="nowDateBalance" prop="nowDateBalance"  />
              <el-table-column label="创建时间" align="center" key="createTime" prop="createTime"  />
              <el-table-column label="更新时间" align="center" key="updateTime" prop="updateTime"  />

            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth.js"
import useAppStore from '@/store/modules/app.js'
import {
  listUser,
  getContract,
  resetUserPwd,
  selectRoleAll,
  getStorechange,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
  listStore,
  blacklist
} from "@/api/system/amount.js"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {addContract, editContract} from "@/api/contract/contractList.js";
// import {selectRoleAll} from "../../../api/company/store.js";

const router = useRouter()
const appStore = useAppStore()
const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex,sys_company_disable} = proxy.useDict("sys_normal_disable", "sys_user_sex","sys_company_disable")
const userList = ref([])
const tableData = ref([])
const open = ref(false)
const bgopen = ref(false)
const infoopen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const names = ref([])
const listStores = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const htdata = ref('')
const dateRange = ref([])
const deptName = ref("")
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const postOptions = ref([])
const roleOptions = ref([])
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,

  // 弹出层标题（用户导入）
  title: "",
  form:{
    blacklistReason:undefined
  },
  rules:{
    blacklistReason: [
      { required: true, message: '请输入原因', trigger: 'blur' }
    ],
  }
})
// 手机号校验规则
const validatePhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('手机号不能为空'));
  }
  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};

// 身份证号校验规则
const validateIdCard = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('身份证号不能为空'));
  }
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
  if (!reg.test(value)) {
    callback(new Error('请输入正确的身份证号码'));
  } else {
    callback();
  }
};

// 银行卡号校验规则
const validateBankCard = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('银行卡号不能为空'));
  }
  const reg = /^[1-9]\d{9,29}$/;
  if (!reg.test(value)) {
    callback(new Error('请输入正确的银行卡号'));
  } else {
    callback();
  }
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    storeName: undefined,
    createTime:undefined,
    startTime:undefined,
    endTime:undefined

  },
  rules: {
    roleId: [
      { required: true, message: '请选择职位', trigger: 'change' }
    ],
    name: [
      { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    gender: [
      { required: true, message: '请选择性别', trigger: 'change' }
    ],
    phone: [
      { required: true, validator: validatePhone, trigger: 'blur' }
    ],
    idCard: [
      { required: true, validator: validateIdCard, trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择是否在职', trigger: 'change' }
    ],
    entryDate: [
      { required: true, message: '请选择入职日期', trigger: 'change' }
    ],
    leaveDate: [
      { required: true, message: '请选择离职时间', trigger: 'change' }
    ],
    storeId: [
      { required: true, message: '请选择所属门店', trigger: 'change' }
    ],
    accountNo: [
      { required: true, validator: validateBankCard, trigger: 'blur' }
    ],
    bankBranch: [
      { required: true, message: '请输入开户行', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val)
})

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
  listStore().then(res=>{
    listStores.value = res.data;
  })
}


/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.deptId = undefined
  // proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.name || names.value
  proxy.$modal.confirm('是否确认删除门店名称为"' + userIds + '"的数据项？').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/customer/export", {
    ...queryParams.value,
  },`user_${new Date().getTime()}.xlsx`)
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row)
      break
    case "handleAuthRole":
      handleAuthRole(row)
      break
    default:
      break
  }
}


/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  names.value = selection.map(item => item.name)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 是否加入黑名单  */
function handleStatusChange(row) {
  console.log(row);
  const { id, isBlacklist } = row;
  console.log(row.isBlacklist)
  let text = row.isBlacklist === '1' ? "加入黑名单" : "退出黑名单";
  upload.form.id = row.id;
  upload.form.isBlacklist = row.isBlacklist
  upload.title = text
  upload.open = true

}
/** 加入黑名单 */
function submitFileForm(row) {
  // blacklist
  proxy.$refs["upload.form"].validate((valid) => {
    if (valid) {
      console.log(upload.form)
       blacklist(upload.form).then(response => {
         console.log(response)
         upload.open = false;
         upload.form.blacklistReason = undefined;
         getList();
       })
    }
  });
}
/*取消*/
function quxiao(){
  upload.open = false;
  upload.form.blacklistReason = undefined;
  getList();
}

/** 导入按钮操作 */
function handleImport(row) {
  upload.title = "加入黑名单"
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/store/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}



/** 重置操作表单 */
function reset() {
  form.value = {
    managerId: undefined,
    name: undefined,
    status: "",
    address: undefined,
    managerPhone: undefined,
    mangerCard: undefined,
    mangerSex: undefined,
    roleId: undefined,
    remark: undefined,
    isIncumbency: undefined,
    incumTime: undefined,
    dimissionTime: undefined,
    isFranchise: undefined,
    accountNumber: undefined,
    accountAdd: undefined,

  }
  proxy.resetForm("userRef")
}

/*查看合同*/
function handleInfo(row){

  const contractNo = row.id
  getContract(contractNo).then(response => {
    console.log(response)
    htdata.value = response.data
    infoopen.value = true
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  bgopen.value = false;
  infoopen.value = false;
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()

  selectRoleAll().then(response => {

    postOptions.value = response.data
    console.log(response)
    open.value = true
    title.value = "添加用户"
    console.log(response)
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  listStore().then(res=>{
    listStores.value = res.rows;
  })
  selectRoleAll().then(response => {
    postOptions.value = response.data
  })
  const userId = row.id || ids.value
  getUser(userId).then(response => {
    form.value = response.data
    postOptions.value = response.posts
    roleOptions.value = response.roles
    form.value.postIds = response.postIds
    form.value.roleIds = response.roleIds
    open.value = true
    title.value = "修改客户"
    form.password = ""
  })
  selectRoleAll().then(response => {
    postOptions.value = response.data
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })

      }
    }
  })
}

onMounted(() => {
  getDeptTree()
  getList()
  /*proxy.getConfigKey("sys.user.initPassword").then(response => {
    initPassword.value = response.msg
  })*/
})
</script>
<style scoped>
.contract-container {
  padding: 20px;
  background: #fff;
}

.contract-header {
  margin-bottom: 20px;
  text-align: center;
  position: relative;
}

.contract-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.contract-no {
  font-size: 14px;
  color: #666;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.info-table {
  margin-bottom: 20px;
}

.person-info {
  margin: 5px 0;
}

.person-info .label {
  color: #666;
  display: inline-block;
  width: 60px;
  text-align: right;
  margin-right: 0;
}
</style>